#pragma once 

#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "log.hpp"
#include <unistd.h>
#include <unordered_map>

#define SIZE 1024

class UdpServer
{
private:
    uint16_t _port; //端口号
    std::string _ip;//ip地址
    int _sock;      //套接字(文件描述符)
    std::unordered_map<std::string,struct sockaddr_in> _users;
public:
    UdpServer(uint16_t port,std::string ip = "")
    :_port(port),_ip(ip),_sock(-1)
    { }

    bool initServer()
    {
        //1.创建套接字
        _sock = socket(AF_INET,SOCK_DGRAM,0);
        if(_sock < 0)
        {
            logMessage(FATAL,"%d:%s",errno,strerror(errno));
            exit(2);
        }

        //2.bind : 将用户设置的ip和port在内核中和我们当前的进程强关联
        struct sockaddr_in local;
        bzero(&local,0);

        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = _ip.empty() ? INADDR_ANY : inet_addr(_ip.c_str());
        
        if(bind(_sock,(struct sockaddr*)&local,sizeof(local)) < 0)
        {
            logMessage(FATAL,"%d:%s",errno,strerror(errno));
            exit(2);
        }

        logMessage(NORMAL, "init udp server done ... %s", strerror(errno));
        return true;
    }

    void start()
    {
        char buffer[SIZE];
        while(true)
        {
            //输出型参数 peer
            struct sockaddr_in peer;
            bzero(&peer,sizeof(peer));
            socklen_t len = sizeof(peer);
            char key[64];
            char result[1024];
            std::string cmd_echo;

            //读取数据
            ssize_t s = recvfrom(_sock,buffer,sizeof(buffer),0,(struct sockaddr*)&peer,&len);
            if(s > 0)
            {
                buffer[s] = 0;
                //1.输出发送的信息
                //2.是谁发的?
                 uint16_t cli_port = ntohs(peer.sin_port);
                 std::string cli_ip = inet_ntoa(peer.sin_addr);
                // printf("[%s:%d]# %s\n",cli_ip.c_str(),cli_port,buffer);

                // if(strcasestr(buffer, "rm") != nullptr || strcasestr(buffer, "rmdir") != nullptr)
                // {
                //     std::string err_message = "坏人.... ";
                //     std::cout << err_message << buffer << std::endl;
                //     sendto(_sock, err_message.c_str(), err_message.size(), 0, (struct sockaddr *)&peer, len);
                //     continue;
                // }

                // FILE* fp = popen(buffer,"r");
                // if(fp == nullptr)
                // {
                //     logMessage(ERROR, "popen: %d:%s", errno, strerror(errno));
                //     continue;
                // }
               
                // while(fgets(result,sizeof(result),fp) != nullptr)
                // {
                //     cmd_echo += result;
                // }
                // fclose(fp);

                snprintf(key,sizeof(key),"%s-%d",cli_ip.c_str(),cli_port);
                logMessage(NORMAL, "key: %s", key);
                auto it = _users.find(key);
                if(it == _users.end())
                {
                    logMessage(NORMAL, "add new user : %s", key);
                    _users.insert({key,peer});
                }
            }

            //写回数据
            //sendto(_sock,buffer,strlen(buffer),0,(struct sockaddr*)&peer,len);
            // sendto(_sock,cmd_echo.c_str(),cmd_echo.size(),0,(struct sockaddr*)&peer,len);

            for(auto& iter : _users)
            {
                std::string sendMessage = key;
                sendMessage += "# ";
                sendMessage += buffer; // 127.0.0.1-1234# 你好
                logMessage(NORMAL, "push message to %s", iter.first.c_str());
                sendto(_sock,sendMessage.c_str(),sendMessage.size(),0,(struct sockaddr*)&(iter.second),sizeof(iter.second));
            }
        }
    }
 
    ~UdpServer()
    {
        if(_sock >= 0)
        {
            close(_sock);
        }
    }

};